using NFreeMarker.Template;

namespace NFreeMarker.Core
{
    internal class ExistsExpression : Expression
    {
        private readonly Expression _exp;

        internal ExistsExpression(Expression exp)
        {
            _exp = exp;
        }

        protected override ITemplateModel _getAsTemplateModel(Environment env)
        {
            ITemplateModel tm = null;
            try
            {
                tm = _exp.GetAsTemplateModel(env);
            }
            catch (InvalidReferenceException)
            {
                if (!(_exp is ParentheticalExpression))
                {
                    throw;
                }
            }
            return tm == null ? TemplateBooleanModel.False : TemplateBooleanModel.True;
        }

        internal override bool IsLiteral()
        {
            return false;
        }

        protected override Expression DeepCloneImpl(string name, Expression subst)
        {
            return new ExistsExpression(_exp.DeepClone(name, subst));
        }

        public override string GetCanonicalForm()
        {
            return _exp.GetCanonicalForm() + "??";
        }
    }
}